package top.lixunda.ecommerce.server.business.api.entity.dto;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import top.lixunda.common.validate.XumValid;
import top.lixunda.common.validate.annotation.XumDefault;
import top.lixunda.common.validate.annotation.XumMin;
import top.lixunda.ecommerce.server.business.api.condition.ILambdaQueryWrapperDTO;

import java.util.function.Function;

/**
 * 分页DTO
 *
 * @author Xumda
 * @version time:2019/12/27 16:05
 */
@SuppressWarnings({"WeakerAccess", "unused"})
@ApiModel("分页DTO")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class PageDTO<T, C extends ILambdaQueryWrapperDTO<T>> {

    /**
     * 分页尺寸，最小为1，-1查询全部不分页
     */
    @ApiModelProperty(value = "分页尺寸", notes = "最小为1")
    @XumDefault(numbers = 10)
    private Long size;

    /**
     * 当前页数，1序开头，最小为1
     */
    @ApiModelProperty(value = "当前页数", notes = "1序开头，最小为1")
    @XumDefault(numbers = 1)
    @XumMin(1)
    private Long current;

    /**
     * 查询条件，可以是其他DTO
     */
    @ApiModelProperty(value = "查询条件")
    @XumValid
    private C condition;

    /**
     * 获取其中的条件Wrapper
     *
     * @return LambdaQueryWrapper
     */
    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public LambdaQueryWrapper<T> getWrapper() {
        return getWrapper(null);
    }

    /**
     * 获取其中的条件Wrapper
     *
     * @param function 自定义条件内容
     * @return LambdaQueryWrapper
     */
    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public LambdaQueryWrapper<T> getWrapper(Function<LambdaQueryWrapper<T>, LambdaQueryWrapper<T>> function) {
        // 是否自带条件
        LambdaQueryWrapper<T> lambdaQueryWrapper = null;
        if (this.condition != null) {
            // 自带条件
            lambdaQueryWrapper = this.condition.toWrapper();
        }
        if (lambdaQueryWrapper == null) {
            lambdaQueryWrapper = new LambdaQueryWrapper<>();
        }
        if (function != null) {
            lambdaQueryWrapper = function.apply(lambdaQueryWrapper);
        }
        return lambdaQueryWrapper;
    }

    /**
     * 获取分页条件
     *
     * @param <R> R
     * @return Page
     */
    @ApiModelProperty(hidden = true)
    @JsonIgnore
    public <R> Page<R> getPage() {
        Page<R> page = new Page<>();
        page.setCurrent(this.getCurrent());
        page.setSize(this.getSize());
        return page;
    }

}
